package dubbo.learn.core.component;

import dubbo.learn.core.component.export.ExportService;
import dubbo.learn.core.component.protocol.ServiceProtocol;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

public class ExportServicePublishBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware {
    private HashMap<Object,Boolean> beanProcessedMap = new HashMap<>();

    private BeanFactory beanFactory;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ExportService) {
            Boolean isAlreadyProcessed = beanProcessedMap.get(bean);
            if (isAlreadyProcessed != null && isAlreadyProcessed) {
                return bean;
            }

            ExportService exportService = (ExportService) bean;
            RMap<Object, Object> map = beanFactory.getBean(RedissonClient.class).getMap(exportService.getExportServiceFullName());

            map.put(getHost() + ":" + beanFactory.getBean(ServiceProtocol.class).getPort(),System.currentTimeMillis());
        }

        return bean;
    }

    public String getHost() {
        try {
            String s = InetAddress.getLocalHost().getHostAddress();
            return s;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

        this.beanFactory = beanFactory;
    }
}
